package com.iye.puretennis.fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.*;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.HuaWenHuPoEditText;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.custom.UserInfoFragment;
import com.iye.puretennis.custom.ViewCache;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserInfo;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.helper.Session;
import com.iye.puretennis.utils.JsonUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/27.
 */
public class SearchFriendFragment extends TabFragment {

    public static final String TAG = "SearchFriendsFragment";

    private HuaWenHuPoEditText searchFriendView;

    private UserListAdapter userListAdapter;

    private List<UserInfo> users = new ArrayList<UserInfo>();

    @Override
    public void onCustomCreateView(LayoutInflater inflater) {

        ListView userListView = (ListView) mainView.findViewById(R.id.user_list_view);

        userListAdapter = new UserListAdapter(R.layout.search_friend_item, inflater);

        userListView.setAdapter(userListAdapter);

        searchFriendView = (HuaWenHuPoEditText) mainView.findViewById(R.id.search_friend_view);

        searchFriendView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {

                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (i == KeyEvent.KEYCODE_ENTER) {
                        searchUsers(searchFriendView.getText().toString());
                    }
                }
                return false;
            }
        });

        ImageButton cancelSearchButton = (ImageButton) mainView.findViewById(R.id.search_cancel_btn);

        cancelSearchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchFriendView.setText("");
                searchUsers("");
            }
        });
    }


    @Override
    public int getViewId() {
        return R.layout.searchfriend;
    }

    @Override
    public int getSourceId() {
        return R.id.search_friend;
    }

    @Override
    public void updateUI() {

    }

    private void searchUsers(final String keyword) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject paramJson = new JSONObject();
                try {

                    paramJson.put("keyword", keyword);
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);

                    final String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS_SEARCH), token.getToken(), paramEntity);
                    if (!result.equals(Constant.RESPONSE_BADLY)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                users.clear();
                                try {
                                    JSONArray jsonArray = new JSONArray(result);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        users.add(JsonUtils.toUserInfo(jsonArray.getString(i)));
                                    }
                                    userListAdapter.notifyDataSetChanged();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    class UserListAdapter extends BaseAdapter {
        private int resource;
        private LayoutInflater inflater;
        private ViewCache viewCache;

        UserListAdapter(int resource, LayoutInflater inflater) {
            this.resource = resource;
            this.inflater = inflater;
        }

        @Override
        public int getCount() {
            return users.size();
        }

        @Override
        public Object getItem(int position) {
            return users.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            HuaWenHuPoTextView nameView;

            ImageView imageView;

            if (convertView == null) {
                convertView = inflater.inflate(resource, null);
                nameView = (HuaWenHuPoTextView) convertView.findViewById(R.id.search_user_name);
                imageView = (ImageView) convertView.findViewById(R.id.user_photo);
                viewCache = new ViewCache(nameView, imageView);
                convertView.setTag(viewCache);

            } else {
                viewCache = (ViewCache) convertView.getTag();
                nameView = viewCache.getNameView();
                imageView = viewCache.getImageView();
            }
            final UserInfo user = users.get(position);
            String name = user.getNickname(token.getGuid());
            nameView.setText(name);

            final String userGuid = user.getGuid();

            loadUserImage(userGuid, imageView);

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Session session = Session.newSession();
                    session.put("userGuid",userGuid);
                    goFragment(R.id.search_friend, UserInfoFragment.TAG, UserInfoFragment.class, null, false);
                }
            });
            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    showPopupMenu(view, R.menu.details_invite_menu, new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {

                            sendFriendRequest(user);

                            return true;
                        }
                    });
                    return true;
                }
            });
            return convertView;
        }
    }

    private void sendFriendRequest(final UserInfo user) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final FragmentActivity activity = getActivity();

                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("guid", user.getGuid());
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS_JOINREQUEST_REQUEST), token.getToken(), paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, getString(R.string.invite_send), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


}
